<template>
    <view class="page-creation-detail">
        <view class="article">
            <view class="title flex-block">
                <u-image width="48rpx" height="48rpx" :src="proxy.$util.getFullImage(info.appUserListVo.avatar)" shape="circle"></u-image>
                <text class="ml-2">{{info.appUserListVo.nickname || info.appUserListVo.username}}</text>
            </view>
            <view class="content">
                <view v-if="info.title" class="title">{{ info?.title }}</view>
                <view v-if="info.articlesType == '2'" class="book mt-2">
                        <view class="flex-block mb-2">
                            <u-image width="240rpx" height="280rpx" :src="proxy.$util.getFullImage(info.coverImageUrl)"></u-image>
                            <view class="ul-li">
                                <view class="li">书名：{{ info.bookName }}</view>
                                <view class="li">作者：{{ info.bookAuthor }}</view>
                                <view class="li">标签：{{ info.tags }}</view>
                                <view class="li">推荐理由：{{ info.recommendationReason }}</view>
                            </view>
                        </view>
                </view>
                <view class="mt-2" v-if="info.articlesType == '0'"><u-image width="100%" mode="widthFix" :src="proxy.$util.getFullImage(info.coverImageUrl)"></u-image></view>
                <view class="my-2 contentHtml" v-html="proxy.$util.resetHtml(info.content)"></view>
                <template v-if="info.articlesType == '1'">
                    <view class="imgs">
                        <image-layout ref="refImageLayout" :imgs="info.imgList" :is-review="true" />
                    </view>
                    <view @click="proxy.$util.gotoPage('/packageB/activity/detail', { id: info.articlesActivitesDto.id })">
                        <u-tag class="activity-tag"
                            :class="getActivitiesName(info.articlesActivitesDto, 'isExpire') ? 'tag-grey' : 'tag-cyan'"
                            shape="circle" :text="getActivitiesName(info.articlesActivitesDto, 'name')"></u-tag>
                    </view>
                </template>
            </view>
            <view class="time">
                    {{ info.createTime }}
            </view>
        </view>
        <view class="comment">
            <view class="mb-2 flex-between">
                <text class="font-bold">评论 {{ info.commentsSum || 0 }}</text>
                <view v-if="info.isCommentDisabled == '1'" class="c-red ft-12">
                    <u-icon name="info-circle-fill"></u-icon>
                    <text class="ml-1">作者关闭了评论</text>
                </view>
                <template v-else>
                    <view v-if="info.sensitiveContentWarning == '1'" class="c-red ft-12">
                        <u-icon name="info-circle-fill"></u-icon>
                        <text class="ml-1">内容涉及心理创伤，请谨慎评论</text>
                    </view>
                </template>
            </view>
            <view class="p-4" v-if="commentList.length == 0">
                <u-empty text="暂无评论" mode="list"></u-empty>
            </view> 
            <view class="fly-card" v-else>
                <view class="item" v-for="(item,index) in commentList" :key="index">
                    <view class="thumb" @click="proxy.$util.gotoPage('/packageB/bolg/index', { userId: item.userId })">
                        <u-image width="48rpx" height="48rpx" :src="proxy.$util.getFullImage(item.appUserListVo.avatar)" shape="circle"></u-image>
                    </view>
                    <view class="content no-border">
                        <view class="title" @click="proxy.$util.gotoPage('/packageB/bolg/index', { userId: item.userId })">{{ item.appUserListVo.nickname || item.appUserListVo.username }}</view>
                        <view class="desc" @click="sendComment(item)">{{ item.content }}</view>
                        <!-- <view class="date">1天前 广州</view> -->
                        <view class="sub-list" v-if="item.replies.length > 0">
                            <view class="item" v-for="(sub,j) in item.replies" :key="j">
                                <view class="title">
                                    <text @click="proxy.$util.gotoPage('/packageB/bolg/index', { userId: sub.userId })">{{ sub.appUserListVo.nickname || sub.appUserListVo.username }}</text>
                                    <template v-if="sub.parent"><text class="c-grey9">回复</text><text @click="proxy.$util.gotoPage('/packageB/bolg/index', { userId: sub.parent.userId })">{{ sub.parent.nickname || sub.parent.username }}</text>：</template>
                                    <template v-else>：</template>
                                </view>
                                <view class="content no-border">
                                    <!-- <view class="title">{{ sub.appUserListVo.nickname || sub.appUserListVo.username }}</view> -->
                                    <view class="desc" @click="sendComment(sub)">{{ sub.content }}</view>
                                    <!-- <view class="date">1天前 广州</view> -->

                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="fly-bottom-bar">
            <view class="content">
                <view class="function">
                    <view v-if="info.isCommentDisabled == '0'" class="input" @click="sendComment()">写点什么...</view>
                    <view v-else></view>
                    <view class="btns">
                        <view class="btn-item" @click="handleLike"><u-image :src="info.yesNoLikes ? proxy.$icon.likePre : proxy.$icon.likeDef" width="42rpx" height="42rpx"></u-image><text class="ml-1">{{info.likesSum || 0}}</text></view>
                        <view class="btn-item" @click="handleFavorite"><u-image :src="info.yesNoFavorites ? proxy.$icon.collectPre : proxy.$icon.collectDef" width="42rpx" height="42rpx"></u-image><text class="ml-1">{{ info.favoritesSum || 0}}</text></view>
                        <view class="btn-item"><u-image :src="proxy.$icon.talk" width="42rpx" height="42rpx"></u-image><text class="ml-1">{{ info.commentsSum || 0 }}</text></view>
                    </view>
                </view>
            </view>
        </view>
        <u-action-sheet :list="actionSheet.list" v-model="actionSheet.isShow" @click="selectActionSheet"></u-action-sheet>
    </view>
</template>
<script setup lang="ts">
import dayjs from 'dayjs';
import ImageLayout from '@/components/ImageLayout/index.vue';
import {apiUrl} from '@/static/js/config'
import { onShow, onLoad } from '@dcloudio/uni-app';
import { useAppStore } from '@/stores/app';
let appStore = useAppStore();
import { useArticleStore } from '@/stores/article';
import { reactive } from 'vue';
let articleStore = useArticleStore();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
let pageParams = reactive({});
let info = ref();
let refImageLayout = ref();
let actionSheet = reactive({
    isShow: false,
    row: {},
    list: [
        {id: '0', text: '回复'},
        {id: '1', text: '删除'},
    ],
});
let commentList = ref([])
const getDetail = () => {
    proxy.$http('get', '/admin/articles/'+pageParams.id, {userId: appStore.userInfo.userId}, (data,msg) => {
        info.value = data;
        info.value.imgList = articleStore.getImageList(data.coverImageUrl);
        setTimeout(() => {
            refImageLayout.value.getImgHeight();
        }, 1000); 
    })
};
const getActivitiesName = (obj, type) => {
    let name = obj.activitiesName;
    let time = dayjs(obj.startTime).format('YYYY-MM-DD');
    let isExpire = dayjs(obj.startTime).isBefore(dayjs(), 'day');
    let title = '报名一起聊！';
    if (isExpire) {
        title = '已完结~'
    }
    if (type == 'name') {
        return title + time + ' ' + name;
    }
    if (type == 'isExpire') {
        return isExpire;
    }
}
const getCommentList = () => {
    proxy.$http('get', '/admin/comments/articles/'+ pageParams.id +'/comments', {articleId: pageParams.id}, (data,msg) => {
        commentList.value = data.map(item => {
            item.replies = getReplies(item.replies);
            return item;
        });
    },msg => {

    })
};
const getReplies = (data, parent) => {
    let arr = [];
    data.forEach((item,index) => {
        // let name = item.appUserListVo.nickname || item.appUserListVo.username;
        // let resName = name;
        // if(parent){
        //     let parentName = parent.nickname || parent.username;
        //     resName = name + '回复' + parentName
        // }
        arr.push({...item, parent});
        if(item.replies.length > 0){
            arr = arr.concat(getReplies(item.replies, item.appUserListVo))
        };
    });
    return arr;
}
const selectActionSheet = (index) => {
    if(index == 0){
        sendComment(actionSheet.row);
    }else{
        uni.showModal({
            title: '提示',
            content: '确定要删除该评论？',
            success: res => {
                if(res.confirm){
                    uni.showToast({title: '删除成功'});
                    getCommentList();
                }
            }
        })
    }
}
const handleComment = (obj) => {
    if(info.value.userId == appStore.userInfo.userId){
        actionSheet.row = obj;
        actionSheet.isShow = true;
    }else{
        sendComment(obj);
    }
    
};
const sendComment = (obj) => {
    let params = {
        articleId: pageParams.id,
        userId: appStore.userInfo.userId,
        content: '',
    };
    let placeholderText = '有话要说，快来评论'
    if(obj){
        params.parentCommentId = obj.id;
        placeholderText = '回复' + (obj.appUserListVo.nickname || obj.appUserListVo.username)
    };
    uni.showModal({
        title: '写下评论',
        content: '',
        placeholderText: placeholderText,
        editable: true,
        success: res => {
            if(res.confirm){
                params.content = res.content;
                articleStore.sendComment(params).then(res => {
                    getDetail();
                    getCommentList();
                })
            }
        }
    })
};
const handleLike = () => {
    if(info.value.yesNoLikes){
        articleStore.deleteLike(info.value.id).then(res => {
            // info.yesNoLikes = false;
            // info.likesSum -= 1;
            getDetail();
        });
    }else{
        let params = {
            articleId: info.value.id,
            userId: appStore.userInfo.userId,
        }
        articleStore.handleLike(params).then(res => {
            // info.yesNoLikes = true;
            // info.likesSum += 1;
            getDetail();
        });
    }
};
const handleFavorite = () => {
    if(info.value.yesNoFavorites){
        articleStore.deleteFavorite(info.value.id).then(res => {
            // info.yesNoFavorites = false;
            // info.favoritesSum -= 1;
            getDetail()
        });
    }else{
        let params = {
            articleId: info.value.id,
            userId: appStore.userInfo.userId,
        }
        articleStore.handleFavorite(params).then(res => {
            // info.yesNoFavorites = true;
            // info.favoritesSum += 1;
            getDetail();
        });
    }
};

onLoad(e => {
    pageParams = e;
});
onShow(() => {
    getDetail();
    getCommentList();
})


</script>
<style>
page{
    height:100%;background:#fff;
}
</style>